package cn.milolab.djback.conf.requestprocessor;

import cn.milolab.djback.bean.response.StandardResponse;
import cn.milolab.djback.conf.DjException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.LinkedHashMap;

/**
 * @author milowang
 */
@RestControllerAdvice
public class ResponseBodyWrapper implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        // 对所有打入请求都启用这个ControllerAdvice
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        if (body instanceof DjException) {
            // 如果是由DjException引发的异常，包装异常返回体
            DjException ex = (DjException) body;
            return new StandardResponse(ex.getStatus().getCode(), ex.getMessage(), null);
        } else if (body instanceof String) {
            // 如果是由spring自动生成的异常信息map,直接返回错误信息
            return body;
        } else if (body instanceof LinkedHashMap) {
            return body;
        } else {
            // API正确执行，包装并返回
            return new StandardResponse(200, null, body);
        }
    }
}
